package com.providera;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

@SpringBootApplication
@Import({SpringUtil.class})
@Slf4j
public class ProviderAApplication {

    public static int SOCKET_PORT;

    public static void main(String[] args) throws IOException {
        socket();
        SpringApplication.run(ProviderAApplication.class);
    }

    private static void socket() throws IOException {
        SOCKET_PORT = NetUtil.getUsableLocalPort();
        ServerSocket serverSocket = new ServerSocket(SOCKET_PORT);
        System.out.println("websocket lister port: " + SOCKET_PORT);
        ThreadUtil.execAsync(() -> {
            while (true) {
                try {
                    Socket socket = serverSocket.accept();
                    //读取一行数据
                    String str = IoUtil.read(socket.getInputStream(), "UTF-8");
                    //通过while循环不断读取信息，
                    System.out.println(str);
                    socket.shutdownInput();


                    // TODO: res is function result
                    String[] split = StrUtil.split(str, "#");
                    Class<?> aClass = Class.forName(split[0]);
                    Object bean = SpringUtil.getBean(aClass);
                    String res = ReflectUtil.invoke(bean, split[1]);
                    System.out.println("get result: " + res);

                    IoUtil.writeUtf8(socket.getOutputStream(), false, res);
                    socket.shutdownOutput();
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                socket.getInputStream().close();
//                socket.getOutputStream().close();
//                socket.close();
            }
        });
    }

}
